// JavaScript Document

// Performance
function loadBgImage(){
	var img = new Image();
	img.src = "../images/all.png";
}

$('html').ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
        // Only send the token to relative URLs i.e. locally.
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});
// Common Function

function getQuerystring(key, default_)
{
  if (default_==null) default_=""; 
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}

function findParentForm(con){
	var ctrl = $(con);
	while(ctrl.attr("nodeName").toLowerCase() != "form"){
		ctrl = ctrl.parent();
		if(ctrl.attr("nodeName").toLowerCase() == "body"){
			return false;	
		}
	}
	return ctrl;
}

function isIpad(){
	return (navigator.userAgent.toLowerCase().indexOf("ipad") > 0)
}

function showPopup(){
  var popupLayer = $("#layer-popup");
  changePopupPostion();
  if($.browser.msie && $.browser.version == "6.0"){
		window.onresize = window.onscroll = function(){
			changePopupPostionForIE6();
		};
  }
}

function addWindowLoadEvent(func){
	var oldonload = window.onload;  
	if (typeof window.onload != 'function') {  
		window.onload = func;  
	} else {    
		window.onload = function() {  
			oldonload();  
			func();
		}  
	}
}

function closePopup(){
  $("#layer-popup").hide();
  $("#layer-over").hide();
}

function changePopupPostion(){
 var overLayer = $("#layer-over");
 var popupLayer = $("#layer-popup");
 var winWidth = window.innerWidth || document.documentElement.clientWidth;
 var winHeight = window.innerHeight || document.documentElement.clientHeight;
 overLayer.css("width",(parseInt(popupLayer.width()) + 20) + "px");
 overLayer.css("height",(parseInt(popupLayer.height()) + 20) + "px");
 overLayer.css("left",(winWidth - parseInt(overLayer.width()))/2).show();
 popupLayer.css("left",(winWidth - parseInt(popupLayer.width()))/2).show();
 overLayer.css("top",(winHeight - parseInt(overLayer.height()))/2).show();
 popupLayer.css("top",(winHeight - parseInt(popupLayer.height()))/2).show();
}

function changePopupPostionForIE6(){
 var overLayer = $("#layer-over");
 var popupLayer = $("#layer-popup");
 var winWidth = window.innerWidth || document.documentElement.clientWidth;
 var winHeight = window.innerHeight || document.documentElement.clientHeight;
 var scroll = $(document).scrollTop();
 overLayer.css("top",(winHeight - parseInt(overLayer.height()) )/2 + scroll);
 popupLayer.css("top",(winHeight - parseInt(popupLayer.height()) )/2 + scroll);
}

function inputMaxLength(con,length){
	var text = $(con).val();
	if(text.length > length){
		$(con).val(text.substring(0,length));
		$(con).focus()
	}
}

function refreshPage(){
	window.location.reload();
}

function submitForm(con){
	var form = findParentForm(control);
	form.submit();
}

function verifyEmail(email){
	var pattern = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
	flag = pattern.test(email);
	return flag;
} 

function transToLogin(con){
	$(con).attr("href","/accounts/login/?next=" + location.pathname);
}

function isLogin(){
	return (-1 != $("#account").text().indexOf("登出"))?true:false;
}
// App Action

function markUseful(review_id){
  $.get("/useful/?id="+review_id,function(data){
    if(data == "error"){alert("你已经为这个评论投过票了！"); }
    else if(data == 'unlogin'){popupLogin()}
    else{
    	$("#comment_"+review_id+"_num").text(function(index,text){return Number(text)+1;});
    	$("#comment_top_"+review_id+"_num").text(function(index,text){return Number(text)+1;})
    }
  });
}

function ignoreApp(app_id){
  $.getJSON("/api/20/ignore-app/?app_id=" + app_id,function(data){
		$("#app-9field-" + app_id).remove();
		refresh9App();
	});
}

function removeMidAppBox(app_id){
	$("#app-9field-"+app_id).remove();
	refresh9App();
}

function toggleOfficeDesc(){
	$('#office-desc-toggle').toggle(
		function(){
			$("#p2").removeClass('hidden').next("a").addClass('hidden');	
			$('#offical-desc').slideToggle()
			$(this).text("( 收起官方简介 )")
		},
		function(){
			$('#offical-desc').slideToggle()
			$(this).text("( 显示官方简介 )")
		}
	);
}

// App Pop Up

function userReview(app_id){
	var mark = arguments[1]?arguments[1]:'u';
	var loginStatus = isLogin();
	$("#list-popup").remove();
	if(loginStatus){
		if("u" == mark || "m" == mark){
			used(app_id);
			//used(app_id);
		}
		if("w" == mark){
			wish(app_id);
		}
	}else{
		popupLogin();
	}
}

function used(app_id){
	$("#review-popup").show();
	$("#review-loading").show();
	$("#review-body").hide();
	if("false" == getCookie("hide_tags")){
		showAdvanceReview();
	}else{
		hideAdvanceReview();
	}
	showPopup();
	clearReviewPopup();
	$("#review-app-id").text(app_id);
	var url = "/api/20/review/get?id=" + app_id + "&t=" + (new Date()).getTime();
	$.getJSON(url,function(data){
		if("undefined" != typeof(data.review)){
			bindReviewPopupInfo(data.review);
		}else{
			paintReviewPage(app_id);
		}
		$("#popup-pop-tags").html(loadPopTags(data.hot_tags));
		bindReviewSubmitEvent();
		bindSyncItems(data.current_user.social);
		checkPopupTags();
		var directVoteValue = $("#direct-vote-form .review_score").val();
		if("" !== directVoteValue){
			$("#appvote .review_score").val(directVoteValue);
			showStarScore("#appvote");
		} 
		$("#review-loading").hide();
		$("#review-body").show();
		changePopupPostion();
	});
	_gaq.push(['_trackPageview','/virtual/review/start/']);
}

function deleteReview(app_id){
	$.get("/api/review/delete/?id=" + app_id, function(data){
		if("{}" == data){
			deleteReviewCallBack(app_id);
		}
	});
}

function deleteReviewCallBack(app_id){
	var path = location.pathname;	
	if(0 == path.indexOf("/price-drops/") || 0 == path.indexOf("/tag/")){
		update9Delete(app_id);
	}else if(0 == path.indexOf("/app/")){
		if($("#wish-button").length == 1){
			$("#wish-button").removeClass("detail-wished-button").addClass("detail-wish-button").unbind("click").removeAttr("onclick").click(function(){
				userReview(app_id,'w');
			});
			reduceWishNum();
		}else{
			refreshPage();
			return;
		}
	}else{
		refreshPage();
		return;
	}
}

function update9Delete(app_id){
	var actionBox = $("#delete-" + app_id).parent();
	var orininalMark = $("#orininalMark-" + app_id).text();
	if("w" == orininalMark){
		reduceWishNum();
	}
	var htmls = "<a onclick='userReview(" + app_id + ",\"u\")' class='smallButton' id='vote-" + app_id + "' href='javascript:;'>评分</a><a onclick='userReview(" + app_id + ",\"w\")' id='wish-" + app_id + "' class='smallButton' href='javascript:;'>想要</a>";
	var button = $("#delete-" + app_id);
	$("#orininalMark-" + app_id).text("");
	button.add(button.prev()).remove();
	actionBox.prepend(htmls);
}

function wish(app_id,con){
	var condition = {
		"id":app_id,
		"mark":'w'
	}
	$.get("/api/20/mark",condition,function(data){
		data = transJSON(data);
		if(data.status){
			wishCallBack(app_id);
		}
	});
}

function wishCallBack(app_id){
	var path = location.pathname;
	if(0 == path.indexOf("/app/")){
		updateAppWish(app_id);
	}else if(0 == path.indexOf("/recommended/")){
		increaseWishNum(app_id,function(){
			removeMidAppBox(app_id);
		});
		return;
	}else if(0 == path.indexOf("/price-drops/") || 0 == path.indexOf("/tag/") || 0 == path.indexOf("/users/")){
		update9Wish(app_id);
	}else if(0 == path.indexOf("/lists/") || 0 == path.indexOf("/search/")){
		updateListWish(app_id);
	}else{
		increaseWishNum(app_id,function(){
			refreshPage();
		});
	}
	increaseWishNum(app_id);
}

function updateAppWish(app_id){
	$("#wish-button").removeClass("detail-wish-button").addClass("detail-wished-button").removeAttr("onclick").unbind("click").click(function(){deleteReview(app_id)});
}

function updateListWish(app_id){
	$("#wish-" + app_id).replaceWith("<a onclick='deleteReview(" + app_id + ")' href='javascript:;' class='wished' id='delete-" + app_id + "'>取消</a>");
}

function update9Wish(app_id){
	$("#wish-" + app_id).replaceWith("<a class='smallButton wish-button smallButton-selected' onclick='deleteReview(" + app_id + ")' id='delete-" + app_id + "' href='javascript:;'>想要</a>");
}



function paintReviewPage(app_id){
	$("#originalMark").text("");
	$("#popup-tile").html("添加收藏：<b>用过</b>");
	var directVoteValue = $("#direct-vote-form .review_score").val();
	if("" !== directVoteValue){
		$("#appvote .review_score").val(directVoteValue);
		showStarScore("#appvote");
	}
}

function bindSyncItems(socials){
	$("#popup-sync input").add("#popup-sync label").hide();
	if(0 == socials.length){
		$("#popup-sync").hide();
		return;
	}else{
		$("#popup-sync").show();
	}
	$.each(socials,function(i){
		if(socials[i] == "sina"){
			$("#popup-sina-sync").attr("checked",true).show().next().show();
		}
		if(socials[i] == "tencent"){
			$("#popup-tencent-sync").attr("checked",true).show().next().show();
		}
		if(socials[i] == "douban"){
			$("#popup-douban-sync").attr("checked",true).show().next().show();
		}
	});
}

function loadPopTags(tags){
	$.each(tags,function(i){
		tags[i] = "<a href='javascript:;' onclick='selectPopTag(this)'>" + tags[i] + "</a>"; 
	});
	return tags.join("");
}

function clearReviewPopup(){
	$("#review-popup-tags").val("");
	$("#review-popup-content").val("");
	$("#appvote .review_score").val(0);
	$("#content-change").val(0);
	showStarScore("#appvote");
	showRemainWords();
	checkRecordLength(document.getElementById('review-popup-content'),140,$("#remainWords"));
}

function bindReviewPopupInfo(review,change){
	$(".popup-mark").show();
	$("#popup-tile").html("<b>更新收藏</b>");
	$("#originalMark").text(review.mark);
	$("#review-popup-tags").val(review.tags);
	$("#review-popup-content").val(review.content);
	$("#appvote .review_score").val(review.score);
	showStarScore("#appvote");
	showRemainWords();
	checkRecordLength(document.getElementById('review-popup-content'),140,$("#remainWords"));
}

function hideAdvanceReview(){
	$("#hide-advance-review").text("添加标签▼");
	$(".popup-user-tags").add(".popup-pop-tags").hide();
}

function showAdvanceReview(){
	$("#hide-advance-review").text("缩起标签▲");
	$(".popup-user-tags").add(".popup-pop-tags").show();
}

function toggleAdvanceReview(){
	if($("#hide-advance-review").text().indexOf("缩起") >= 0){
		hideAdvanceReview();
		setCookie("hide_tags",true);
		changePopupPostion();
	}else{
		showAdvanceReview();
		setCookie("hide_tags",false);
		changePopupPostion();
	}
}

function showRemainWords(){
	$("#review-popup-content").bind("change",function(){checkRecordLength(this,140,$("#remainWords"))})
		.bind("keyup",function(){
			checkRecordLength(this,140,$("#remainWords"));
			if("0" == $("#content-change").val()){
				_gaq.push(['_trackPageview','/virtual/review/entry_content/']);
			}
			$("#content-change").val("1");
		});
	$("#review-popup-tags").attr("maxlength",300).bind("keyup",function(){checkPopupTags();});
}

function showStarScore(form){
	var form = $(form);
	if(0 == form.length){
		return;
	}
	var score = form.find(".review_score").val();
	var url = form.find("#star1").attr("src").replace(0,2);
	var imgs = form.find(".stars");
	var url0 = "";
	if(url.indexOf("bstar") != -1){
		url0 = "/media/static/images/bstar0.png";
	}else{
		url0 = "/media/static/images/star0.png";
	}
	$.each(imgs,function(i){
		$(imgs[i]).attr("src",url0);
	});
	for(var i=0;i<score;i++){
	 form.find("#star" + parseInt(i + 1)).attr("src",url);
	}
	showStarMessage(form,score);
}

function starMouseAction(control,type){
	var form = findParentForm(control);
	control = $(control);
	var scoreInput = form.find(".review_score");
	var score = (control.attr("id")).substring(4,5);
	var oScore =scoreInput.val();
	if("click" === type){
		 scoreInput.val(score);
	}
	
	var field = (type == 'click')?2:((type == 'over')?"1":"0");
	var ofield = control.attr("src").substring((control.attr("src").length - 5),(control.attr("src").length - 4));
	var url = control.attr("src").replace(ofield,field);
	for(var i=0;i<score;i++){
	 form.find("#star" + parseInt(i + 1)).attr("src",url);
	}
	if("click" === type){
		url = control.attr("src").replace(field,0);
		for(var i=(parseInt(score)+1);i<=5;i++){
			form.find("#star" + i).attr("src",url);
		}
	}
	showStarMessage(form,score);
	if("out" === type){
	 url = control.attr("src").replace(field,2);
	 for(var i=0;i<oScore;i++){
			form.find("#star" + parseInt(i + 1)).attr("src",url);
		 }
	 showStarMessage(form,oScore);
	}
}

function showStarMessage(form,score){
  control = $(form).find(".starMessage");
  var messages = new Array("","很差","较差","一般","推荐","力荐");
  control.html(messages[score]);
}

function toggleVote(type){
	if('w' == type){
		$(".popup-vote").hide();
		if($("#hide-advance-review").text().indexOf("高级") >= 0){
			$(".popup-comment").hide();
			$(".popup-reminds").hide();
		}else{
			$(".popup-comment").show();
			$(".popup-reminds").show();
		}
		changePopupPostion();
	}else{
		$(".popup-vote").show();
		$(".popup-comment").show();
		$(".popup-reminds").show();
		changePopupPostion();
	}
}

function checkRecordLength(con,max,field){
	var area = $(con);
	var remain = max - area.val().length;
	if( 0 <= remain){
		field.html(remain);
	}else{
		field.html(0);
		area.val(area.val().substring(0,max));
	}
}

function selectPopTag(con){
	var control = $(con);
	var tagsInput = $("#review-popup-tags");
	var tags = tagsInput.val().split(" ");
	var type = (control.attr("class") == "tag-selected")?"remove":"select";
	if("remove" == type){
		control.removeClass("tag-selected");
		removePopupTag(tags,control.html())
	}else{
		control.addClass("tag-selected");
		addPopupTag(tags,control.html());
	}
	return false;
}

function addPopupTag(tags,target){
	tags.push(target);
	$("#review-popup-tags").val(tags.join(" ")).focus();
}

function removePopupTag(tags,target){
	tags = $.grep(tags,function(n,i){
		return n != target;
	});
	$("#review-popup-tags").val(tags.join(" ")).focus();
}

function checkPopupTags(){
	var tags = $("#review-popup-tags").val().split(" ");
	var popTags = new Array();
	var tagsA = $(".popup-pop-tags a");
	var selectTags = $(".popup-pop-tags a[class='tag-selected']");
	selectTags.removeClass("tag-selected");
	var newTags = new Array();
	var removeTags = new Array();
	$.each(tagsA,function(i,n){
		popTags.push($(n).html());
	});
	$.each(popTags,function(i){
		$.each(tags,function(n){
			if(popTags[i] == tags[n]){
				$(tagsA[i]).addClass("tag-selected");
				newTags.push(i);
			}
		});
	});
}

function submitPopupReview(){
	$(".review-submit-button").unbind("click");
	var app_id = $("#review-app-id").text();
	var condition = {
		"id":app_id,
		"mark":'u',
		"score":$("#appvote").find(".review_score").val(),
		"tags":$("#review-popup-tags").val(),
		"content":$("#review-popup-content").val(),
		"syncsina":$("#popup-sina-sync:visible:checked").length == 1?"share":"",
		"syncrenren":$("#popup-renren-sync:visible:checked").length == 1?"share":"",
		"synctencent":$("#popup-tencent-sync:visible:checked").length == 1?"share":"",
		"syncdouban":$("#popup-douban-sync:visible:checked").length == 1?"share":""
	}
	$("#review-loading-image").show();
	$.post("/api/20/review/",condition,function(data){
		usedCallBack(data,app_id);
		_gaq.push(['_trackPageview','/virtual/review/submit/']);
	});
}

function bindReviewSubmitEvent(){
	$(".review-submit-button").removeClass("a-btn-disable");
	$("#normal-review-button").click(function(){
		submitPopupReview();
	});
}

function showMagicHat(){
	$("#recommended-tab a").css("background","url('/media/static/images/nav_light.jpg') no-repeat center");
	$("#recommended-tab a span").hide();
	$("#recommended-tab[class*='selected']").find(".nav-selected-left").hide();
	$("#recommended-tab[class*='selected']").find(".nav-selected-right").hide();
	$("#recommended-tab a em").css("display","inline-block");	
}

function hideMagicHat(){
	$("#recommended-tab a").attr("style","");
	$("#recommended-tab a span").show();
	$("#recommended-tab[class*='selected']").find(".nav-selected-left").show();
	$("#recommended-tab[class*='selected']").find(".nav-selected-right").show();
	$("#recommended-tab a em").css("display","none");	
}

function usedCallBack(data,app_id){
	$("#review-loading-image").hide();
	var path = location.pathname;
	var originalCon = ($("#app-9field-" + app_id).length > 0)?$("#app-9field-" + app_id):($("#app-logo-" + app_id).length > 0)?$("#app-logo-" + app_id):($("#app_" + app_id).length > 0)?$("#app_" + app_id):null;
	var targetCon = $("#recommended-tab");
	showMagicHat();
	if(0 == path.indexOf("/users/") || 0 == path.indexOf("/app/")){
		closePopup();
		moveAtoB(originalCon,targetCon,function(){
			hideMagicHat();
			refreshPage();
		});
	}else if(0 == path.indexOf("/recommended/")){
		closePopup();
		moveAtoB(originalCon,targetCon,function(){
			hideMagicHat();
			removeMidAppBox(app_id);
		});
	}else if(0 == path.indexOf("/price-drops/") || 0 == path.indexOf("/tag/")){
		closePopup();
		moveAtoB(originalCon,targetCon,function(){
			hideMagicHat();
			update9Used(app_id);
		});
	}else{
		hideMagicHat();
		refreshPage();
	}
	var originalMark = $("#orininalMark-" + app_id).text();
	if("w" == originalMark){
		reduceWishNum();
	}
	if("r" == originalMark){
		reduceWFRNum();
	}
	$("#orininalMark-" + app_id).text("u");
}

function update9Used(app_id){
	var actionBox = $("#vote-" + app_id).parent();
	var htmls = "<a onclick='userReview(" + app_id + ",\"m\")' class='smallButton' id='vote-" + app_id + "' href='javascript:;'>修改</a><a onclick='deleteReview(" + app_id + ")' id='delete-" + app_id + "' class='smallButton' href='javascript:;'>删除</a>";
	actionBox.find("span").add(actionBox.find("a[id^='vote']")).add(actionBox.find("a[id^='delete']")).add(actionBox.find("a[id^='wish']")).remove();
	actionBox.prepend(htmls);
}

function increaseWishNum(app_id,func){
	var originalCon = ($("#app-9field-" + app_id).length > 0)?$("#app-9field-" + app_id):($("#app-logo-" + app_id).length > 0)?$("#app-logo-" + app_id):($("#app_" + app_id).length > 0)?$("#app_" + app_id):null;
	var targetCon = $("#wish-num")
	if(null == originalCon){
		targetCon.text(parseInt(targetCon.text()) + 1);
		return;
	}
	moveAtoB(originalCon,targetCon,function(){
		if("function" == typeof(func)){
			func();
		}
		$(".wish-num").text(parseInt(targetCon.text()) + 1);
		if($("#orininalMark-" + app_id).text() == "r"){
			reduceWRFNum();
		}
		$("#orininalMark-" + app_id).text("w");
	});
}

function reduceWishNum(){
	$(".wish-num").text(parseInt($("#wish-num").text()) - 1);
}

function reduceWRFNum(){
	$(".wfr-num").text(parseInt($("#wfr-num").text()) - 1);
}


function moveAtoB(from,to,funcs){
	var cloneFrom = from.clone().attr("id","from-clone").css("opacity","0.6");
	cloneFrom.css({
		'width' : from.css('width'),
		'height': from.css('height') ,
		'position' : 'absolute',
		'top' : from.offset().top,
		'left' : from.offset().left              
 }).appendTo("body");
	cloneFrom.animate({ 
		width: to.innerWidth(), 
		height: to.innerHeight(), 
		top: to.offset().top, 
		left: to.offset().left,
		opacity: 0
	}, { duration: 600 , complete: function(){
				cloneFrom.remove();
				if("function" == typeof(funcs)){
					funcs();
				}
		 } 
	})
}

function updateAppAction(app_id){
	var actions;
	var field;
	if(0 != $("#app_" + app_id).find(".app-action").length){
		field = $("#app_" + app_id).find(".app-action");
		actions = "<a onclick='userReview(" + app_id + ")' href='javascript:;'>修改</a><a href='javascript:;' onclick='deleteReview(" + app_id + ")'>删除</a>";
	}else{
		field = $("#app-9field-" + app_id).find(".actions");
		actions = "<a onclick='userReview(" + app_id + ")' href='javascript:;' class='smallButton'>修改</a><a href='javascript:;' onclick='deleteApps9Review(" + app_id + ")' class='smallButton'>删除</a>";
	}
	field.html(actions);
}

function deleteApps9Review(app_id){
	var url = "/api/20/review/delete/?id=" + app_id;
	$.get(url,function(data){
		if("{}" === data.toString()){
			$("#app-9field-" + app_id).find(".actions").html("<a class=\"smallButton\" onclick=\"userReview(" + app_id + ",\'u\')\" href='javascript:;'>用过</a><a class=\"smallButton\" onclick=\"userReview(" + app_id + ",\'w\')\" href='javascript:;'>想要</a>");
			//refreshComments($("#app-my-review-id").text(),"delete");
		}else{
			if("undefined" != typeof(data.message)){
				alert(data.message);
			}
		}
	});
}

function getReviewFromType(){
	var path = location.pathname;
	if(0 == path.indexOf("/app/")){
		return "app"
	}
	if(0 == path.indexOf("/recommended/")){
		return "recommended"
	}
	if(0 == path.indexOf("/price-drops/")){
		return "list"
	}
	if(0 == path.indexOf("/tags/")){
		return "list"
	}
}

function reviewForRecommended(){
	var app_id = $("#review-app-id").text();
	$("#app_" + app_id).hide();
}



// App Comment & Reply
function bindTextareaLength(con){
	con.find("textarea").bind("change",function(){
		inputMaxLength(this,300);
	}).bind("keyup",function(){
		inputMaxLength(this,300);
	});
}

function transJSON(data){
	return eval('(' + data + ')');
}

function popupLogin(){
 	showPopup();
	$("#download-popup").hide();
	$("#login-popup").show();
	changePopupPostion();
}

function addReplyToComment(data,id){
	if("Done" == data.status){
		data.is_owner = true;
		addReplyToList(data,id);
		$("#comment-reply-" + id).find("textarea").val("");
		$("#comment_" + id + "_reply_num").text(parseInt($("#comment_" + id + "_reply_num").text()) + 1);
	}else{
		alert("揣着的程序出错了 o(>﹏<)o")
	}
}

function trimCon(con){
	$(con).val($.trim($(con).val()));
}

//register
function registerByForm(con){
	var isPost = true;
	if($(con).attr("class").indexOf("disable") >= 0){
		return;
	}
	var inputs = $("#register-form input[type='text']").add("#register-form input[type='password']");
	$.each(inputs,function(i){
		if($.trim($(inputs[i]).val()) == ""){
			$(this).parent().find(".error").html("").text("（必填）");
			isPost = false;
		}else{
			$(this).parent().find(".error").html("");
		}
	});
	var email = $.trim($("#id_email").val());
	if(!verifyEmail(email)){
		$("#id_email").next().text("请输入有效的Email地址");
		isPost = false;
	}
	var nickname = $.trim($("#id_nick_name").val());
	if(nickname.indexOf("揣着") != -1){
		$("#id_nick_name").next().text("昵称不能包含揣着哦");
		isPost = false;
	}
	var password = $.trim($("#id_password1").val());
	if(password == ""){
		$("#password-message").hide();
	}
	if(password.length < 4 && password != ""){
		$("#id_password1").parent().find(".error").text("密码长度不足4位");
		$("#password-message").hide();
		isPost = false;
	}
	var repassword = $.trim($("#id_password2").val());
	if(repassword != password && repassword != ""){
		$("#id_password2").parent().find(".error").text("前后密码输入不一致");
	}
	if(isPost){
		$("#register-form").submit();
	}
}

// ajax 登录
function ajax_login(){
  var error = $("#form-error");
  error.empty();
  var username = $("#id_username").val()
  var password = $("#id_password").val()
  var remember_me = $("#id_remember_me").attr('checked')
  var csrfmiddlewaretoken = $("input[name='csrfmiddlewaretoken']").val()
  $.post('/api/20/login/',{'username':username,'password':password,
                                  'remember_me':remember_me,
                                  'csrfmiddlewaretoken':csrfmiddlewaretoken},
        function(data){
          data = transJSON(data);
          if("undefined" != typeof(data.code)){
          	error.text("Email或密码输入有误");
			changePopupPostion();
          }
          else{
          	window.location.reload();
          }
        }
  );
  
}

function clearErrorMessage(con){
  var error = con;
  if("" != error.text()){
	error.empty();
  }
}

//search

function clearSearchInput(con,text){
	if(text == $(con).val()){
		$(con).val("");
	}
}

function checkSearchInput(con,text){
	if("" == $(con).val()){
		$(con).val(text);
	}
}

function toggleSubmitBtn(){
	var type = $("#id_agreement").attr("checked");
	if(true == type){
		$("#btn_submit").removeClass("rectangle-small-button-disable");
	}else{
		$("#btn_submit").addClass("rectangle-small-button-disable");
	}
}

function toggleSubmitLink(url,func){
	var type = $("#id_agreement").attr("checked");
	if(true == type){
		$("#link_submit").removeClass("a-btn-disable").attr("href",url);
		if("function" == typeof(func)){
			$("#link_submit").unbind("click").bind("click",function(){ func(); });
		}
	}else{
		$("#link_submit").addClass("a-btn-disable").attr("href","javascript:;").unbind("click");
	}
}

function changeTopItem(con){
	var type = $(con).val();
	location.pathname = "/top/" + type + '/';
}

// animation
var _moving;
function showBoxH(speed){
	var $cur = 1;
	var $i = 1;
	var $len = $('.animation-h-box .showbox-h>ul>li').length;
	var $pages = Math.ceil($len / $i);
	var $w = $('.animation-h-box').width();
	var $showbox = $('.showbox-h');
	var $num = $('.scroll-paging .num li')
	var $pre = $('.showbox-h-left')
	var $next = $('.showbox-h-right');
	var $speed = speed;
	//向前滚动
	$pre.click(function(){
		if (!$showbox.is(':animated')) { 
			if ($cur == 1) { 
			$showbox.animate({
				left: '-=' + $w * ($pages - 1)
			}, $speed); 
			$cur = $pages; 
		}
		else {
			$showbox.animate({
				left: '+=' + $w
			}, $speed); 
			$cur--; 
		}
		$num.eq($cur - 1).addClass('numcur').siblings().removeClass('numcur'); 
	}
	});
	//向后滚动
	$next.click(function(){
		if (!$showbox.is(':animated')) { 
			if ($cur == $pages) { 
				$showbox.animate({
					left: 0
				}, $speed); 
			$cur = 1; 
		}
		else {
			$showbox.animate({
				left: '-=' + $w
			}, $speed);
			$cur++; 
		}
		bindAnimationImgs($cur);
		$num.eq($cur - 1).addClass('numcur').siblings().removeClass('numcur'); 
	}
	});
	//数字点击事件
	$num.click(function(){
		if (!$showbox.is(':animated')) { 
			var $index = $num.index(this); 
			$showbox.animate({
				left: '-' + ($w * $index)
			}, $speed);
			$cur = $index + 1; 
			bindAnimationImgs($cur);
		$(this).addClass('numcur').siblings().removeClass('numcur'); 
	}
	});
	var $boxes = $showbox.add($num).add($pre).add($next);
	$boxes.mouseover(function(){
		clearInterval(_moving);
	}).mouseout(function(){
		_moving=setInterval(function(){
			$next.click();
		},6000);
	});
	$showbox.trigger('mouseout');
}

function showBoxV(speed){
	var _wrap=$('#discount-box');
	var _interval=speed;
	var _moving;
	_wrap.hover(function(){
			clearInterval(_moving);
		},function(){
				_moving=setInterval(function(){
				var _field=_wrap.find(".app-box-basic-small:first");
				var _h=_field.height();
				_field.animate({marginTop:-_h+'px'},600,function(){
				_field.css('marginTop',0).appendTo(_wrap);
			})
		},_interval)
	}).trigger('mouseleave');
}

function showNotice(speed){
	var _wrap=$('.notice-list-content ul');
	var _interval=speed;
	var _moving;
	$("#notice-board").hover(function(){
			clearInterval(_moving);
		},function(){
				_moving=setInterval(function(){
				var _field=_wrap.find("li:first");
				var _h=_field.width();
				_field.animate({marginLeft:-_h+'px'},600,function(){
				_field.css('marginLeft',0).appendTo(_wrap);
			})
		},_interval)
	}).trigger('mouseleave');
	
	var _next = $(".notice-board-more");
	_next.click(function(){
		var _field=_wrap.find("li:first");
		var _h=_field.width();
		_field.animate({marginLeft:-_h+'px'},600,function(){
			_field.css('marginLeft',0).appendTo(_wrap);
		});
	});
}

//Show Offical Desc
function showCZDesc(){
	$("#offical-desc").fadeOut(400,function(){
		$("#cz-desc").fadeIn(400);
	});
}

function showOfficalDesc(){
	$("#cz-desc").fadeOut(400,function(){
		$("#offical-desc").fadeIn(400);
	});
}

// 翻译

function translate(){
	var transLink = $("#translate");
	type = transLink.data().type;
	original = transLink.data().original;
	if(type == null){
		if($("#p2").length == 0){
			var text = $("#p1").html();
		}else{
			var text = $("#p1").html() + $("#p2").html();
		}
		var defaultMaxLengthPerCall = checkMaxLength(original);
		var key = "ABQIAAAAfHXXE7ZvtGwS8PJkTNLZhBToKuM5WpaIjunuPK8TMCSxGEZyGBRSYuh8D1tzCejzT3vKdQY40QYGXg";
		var src_lang    = original;
		var target_lang = 'zh-CN';
		var url = 'https://ajax.googleapis.com/ajax/services/language/translate';
		var data = {
				'q' : '' + text,
				'v': '1.0',
				'langpair': src_lang + '|' + target_lang,
				'format':'html',
				'key':key
		}
		$("#app-desc-content").hide();
		$("#translate-eng").append("<p id='waiting'>翻译正在进行中...</p>").show();
		setTimeout('checkTranslateFail()',10000);
		if((text.length / defaultMaxLengthPerCall)<1){
			ajaxTranslateOne(url,data);
			
		}else{
			
			var content = new Array();
			var translated = new Array();
			while (text != null && text.length != 0) {
				var sCallPart = text.substring(0, defaultMaxLengthPerCall);
				content.push(sCallPart);
				translated.push("");
				text = text.substring(defaultMaxLengthPerCall);
			}
			for(var i=0;i<content.length;i++){
				try {
					var callPart = content[i];
					data.q = callPart;
					ajaxTranslateMore(url,data,translated,i);
				} catch(e) {
					$("#translate-eng").show().append("<p>翻译出现异常，请稍后再试...</p>");
				}
			}
		}
		$("#translate").data().type = "zh-CN";
		$("#translate a").text("取消翻译");
	}else if(type === "zh-CN"){
		$("#translate-eng").hide();
		$("#app-desc-content").show();
		$(".more").hide();
		$("#p2").show();
		$("#translate").data().type = original;
		$("#translate a").text("使用 Google 翻译为中文");
	}else{
		$("#translate-eng").show();
		$("#app-desc-content").hide();
		$("#translate").data().type = "zh-CN";
		$("#translate a").text("取消翻译");
	}
}

function checkMaxLength(type){
	var num = 1000;
	switch(type){
		case "iw":
			num = 350;
			break;
		case "ar":
			num = 350;
			break;
		default:
			num = 1000;
	}
	return num;
}

function ajaxTranslateOne(url,data){
	try{
		$.ajax({
			url: url,
			dataType: 'jsonp',
			data: data,
			success:function(result){
							if (result.responseData.translatedText) {
							$("#waiting").remove();
							$("#translate-eng").show().append(result.responseData.translatedText);
							$("#app-desc-content").hide();
							$("#more-desc-link").hide();
							
						}
					},
			error:function(){
				translateFail();
			}
		});
	}catch(e){
		translateFail();
	}
}

function translateFail(){
	$("#translate-eng").show().append("<p class='orange'>翻译异常...</p>");
	$("#translate").data().type = "zh-CN";
}

function checkTranslateFail(){
	if("" === $.trim($("#translate-eng").text().replace("翻译正在进行中...",""))){
		$("#translate-eng").empty();
		translateFail();
	}
}

function ajaxTranslateMore(url,data,translated,number){
	try{
		$.ajax({
			url: url,
			dataType: 'jsonp',
			data: data,
			success:function(result){
						if (result.responseData.translatedText) {
							translated[number] = result.responseData.translatedText
						}
						var status = true;
						for(var i=0;i<translated.length;i++){
							if(translated[i] ==""){
								status = false;
								break;
							}
						}
						if(status){
							var content = translated.join();
							$("#waiting").remove();
							$("#translate-eng").show().append(content);
							$("#app-desc-content").hide();
							$("#more-desc-link").hide();
							
						}
					},
			error:function(){
				translateFail();
			}
		});
	}catch(e){
		translateFail();
	}
}


function checkTranslate(){
	var text = $("#p1").text() + $("#p2").text();
	var url = "https://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=" + text.substr(0,200);
	try{
		$.ajax({
			url: url,
			dataType: 'jsonp',
			success:function(result){
						if(result.responseData.language !="zh-CN"){
							$("#translate").show();
							$("#translate").data().original = result.responseData.language ;
						}
					},
			error:function(){
				$("#translate").hide();
			}
		});
	}catch(e){
		$("#translate").hide();
	}
}

function checkDescHeight(){
	var con = $("#app-desc-content");
	if(con.height() < 250){
		con.removeClass("min-desc");
		$("#more-desc-link").hide();
	}
}

// Tip

function closeComment(name){
	$("#" + name).hide();
}

function showDisountTip(){
	$("#discount-tip").show().removeClass("hidden");
	var pos = $("#discount-li").position();
	$("#discount-tip").css("top",pos.top + 31).css("left",pos.left - 150);
}

function closeTip(con){
	var ctrl = $(con);
	while(ctrl.parent().attr("class") != "tip"){
		ctrl = ctrl.parent();
	}
	ctrl.parent().hide();
}

// Big Tip

function showDetailTip(con){
	var con = $(con);
	var tip = $('.app-detail-tip');
	var content = $('.app-details', con).html();
	var index;
	var list = con.parent().find(".app-box-simple-big");
	var leftList = [4,5,10,11];
	$.each(list,function(i){
		if(con.attr("id") == $(list[i]).attr("id")){
			index = i;
			return false;
		}
	});
	tip.empty().append(content);
	if($.inArray(index,leftList)>=0){
		tip.css('top',con.offset().top).css('left',con.offset().left + con.width() - 400)
			.append("<span class='arrow-right'></span>");
	}else{
		tip.css('top',con.offset().top).css('left',con.offset().left + con.width() + 10)
			.append("<span class='arrow-left'></span>");
	}
	tip.show();
}

function hiddenDetailTip(){
	$('.app-detail-tip').hide();
}

function showSmallFloatBox(con){
	$("#float-comment").remove();
	var con = $(con);
	var top = con.position().top + con.height() + 5;
	var left = con.position().left;
	var box = "<div class='float-small-box' id='float-comment'></div>";
	$("body").append(box);
	box = $("#float-comment");
	box.css("top",top).css("left",left);
}

// List 
function show_add_list_item_popup(){
  showPopup();
  $('#layer-popup').html($('#add_list_item_popup').html())
  changePopupPostion();
}

function add_list_item(list_id){
  app_url = $('#layer-popup #id-app-url').val()
  url = "/lists/"+list_id+"/add/?url="+app_url
  $.get(url,function(data){
    if(data == 'error'){$("#layer-popup #error-msg").show();changePopupPostion();}
    else{window.location.href='/lists/'+list_id+"/?edit="+data+"#item"+data};
  });
}

function add_to_list(app_id){
  app_name = $(".big-title").text()
  url = "/lists/add_to_list/"+app_id+"/?app_name="+app_name
  $.get(url,function(data){
		$("#review-popup").hide();
		$("#list-popup").hide();
    $("#layer-popup").append(data);
    changePopupPostion();
  });
}

function hideListPopup(){
	$("#list-popup").remove();
}

//UNREAD

function closeUnRead(){
	$("#unread-message").remove();
	$.get("/clean-alert/");
}

//Social Binding
function directBindingLogin(){
	$("#child-window-status").val("normal");
}

function gotoSocial(con){
	var type = $(con).text();
	var url = getSocialUrl(type);
	window.open(url);
}

function getSocialUrl(type){
	var url = "";
	switch(type){
		case "新浪微博":
			url = "http://weibo.com";
			break;
		case "腾讯微博":
			url = "http://t.qq.com";
			break;
		default:
			url = "/";
	}
	return url;
}

//toggle root login box
function toggleLoginBox(){
	$("#login-box-link").toggle(
		function(){
			showLoginBox();
		},
		function(){
			hideLoginBox();
		}
	);
}

function hideLoginBox(){
	$("#login-box-link").text("登录 ▼");
	$("#login-box-link").removeClass("shadow");
	$("#mini-login-box").hide();
}

function showLoginBox(){
	$("#login-box-link").text("登录 ▲");
	$("#login-box-link").addClass("shadow");
	var pos = $("#login-box-link").position();
	$("#mini-login-box").css("left",pos.left - 151).css("top",pos.top + 18).show();
}

function loginBoxAjaxLogin(){
	$("#mini-login-error").hide().text("");
	var condition = {
		"username":$("#mini-login-username").val(),
		"password":$("#mini-login-password").val(),
		"remember_me":$("#mini-login-agreement").attr("checked")
	}
	if("" === condition.username){
		$("#mini-login-error").show().text("您还没输入用户名呢");
		return;
	}
	if("" === condition.password){
		$("#mini-login-error").show().text("您还没输入密码呢");
		return;
	}
	if(false === verifyEmail(condition.username)){
		$("#mini-login-error").show().text("您输入的用户名格式不正确");
		return;
	}
	ajaxLogin(condition,loginBoxCallBack);
}

function loginBoxCallBack(data){
	if("done" == data.toLowerCase()){
		refreshPage();
	}else{
		$("#mini-login-error").show().text("用户名密码错误");
	}
}


//Social Login
function socialLogin(catagory,type){
	$("#login-next").val(location.pathname);
	var url = getSocialLoginUrl(catagory,type);
	$("#child-type").val("external");
	var socialWindow = window.open(url);
	var waitingSocial = setInterval(function(){
		if(socialWindow.closed){
			window.clearInterval(waitingSocial);
			var nextPath = $("#login-next").val();
			if("close" !== nextPath.toLowerCase() && "external" !== $("#child-type").val()){
				if(nextPath.indexOf("register") < 0 && nextPath.indexOf("login") < 0){
					location.pathname = nextPath;
				}else{
					location.pathname = "/";
				}
			}
		}
	},100);
}

function getSocialLoginUrl(catagory,type){
	var para = "";
	if("undefined" !== typeof(type) && "bind" == type){
		para = "?self-bind=true"
	}
	var url = "";
	switch(catagory){
		case "sina":
			url = "/social/sina/login" + para;
			break;
		case "qq":
			url = "/social/tencent/login" + para;
			break;
		default:
			url = "/";
	}
	return url;
}

function bindNextPath(){
	$("#login-next").val(getQuerystring("next","/"));
}


// Quick Review
function submitQuickReview(id){
	$("#quick-review-error").text("");
	var condition = {
		"mark":"u",
		"id":id,
		"score":$("#app-quick-review-form .review_score").val(),
		"tags":"",
		"content":$("#app-quick-review-content").val()
	}
	if("0" === $.trim(condition.score)){
		$("#quick-review-error").text("不打分可不行哦...");
		return;
	}
	if("" === $.trim(condition.content)){
		$("#quick-review-error").text("不写评论可不行哦...");
		return;
	}
	$.post("/api/20/review",condition,function(){
		window.location.reload();
	});
}

function quickReviewContentCheck(){
	var reaminWordsCon = $("#quick-review-remain");
	$("#app-quick-review-content").bind("change",function(){
		checkRecordLength(this,140,reaminWordsCon)
	}).bind("keyup",function(){
		checkRecordLength(this,140,reaminWordsCon)
	});
}

function showDownload(con){
	$(con).hide();
	var downloadButton = $(con).parent().find(".price-download").fadeIn();
}

function openDownloadPage(itunesUrl,appid){
	if("True" == $("#ispricedrop-" + appid).text() || "true" == $("#ispricedrop-" + appid).text()){
		var price = $("#price-" + appid).text();
		var gap = parseFloat($("#original-price-" + appid).text().replace("$","")) - parseFloat(price);
		_gaq.push(['_trackEvent', 'price_drop', ("0.0" == price)?"free":"paid", gap]);
	}
	if(("True" == $("#ispricedrop-" + appid).text() || "true" == $("#ispricedrop-" + appid).text()) && !isLogin()){
		if("false" == getCookie("is_not_download_popup") || "" == getCookie("is_not_download_popup")){
			openDownloadWindow(itunesUrl,appid);
			return false;
		}else{
			startDownload(itunesUrl,appid);
			return true;
		}
	}else{
		startDownload(itunesUrl,appid);
		return true;
	}
}

function openDownloadWindow(itunesUrl,appid){
	showPopup();
	var price = parseFloat($("#price-" + appid).text().replace("$",""));
	var oprice = parseFloat($("#original-price-" + appid).text().replace("$",""));
	var discount = oprice - price;
	$("#popup-download-button").click(function(){
		storeDownloadPopupStatus();
		startDownload(itunesUrl,appid);
		closePopup();
	});
	$("#download-discount-amount").text("$" + discount);
	$("#login-popup").hide();
	$("#download-popup").show();
	changePopupPostion();
}

function storeDownloadPopupStatus(){
	var isOpen = $("#download-popup-check").attr("checked");
	setCookie("is_not_download_popup",isOpen);
}

function startDownload(itunesUrl,appid){
	var path = location.pathname;
	if(0 < path.indexOf("/wish/") && $("#isself").text() == "true"){
		moveToWFR(appid,itunesUrl);
	}else{
		openItunes(itunesUrl,appid);
		addWFR(appid);
	}
	var appname = appid + "/" + $("#name-" + appid).text();
	_gaq.push(['_trackEvent', 'Download', 'itunes', appname ,parseInt(100 * parseFloat($("#price-" + appid).text()))]);
}

function pushCrack(name, price){
	_gaq.push(['_trackEvent', 'Download', 'crack', name, parseInt(price * 100)]);
}

function openItunes(itunesUrl,appid){
	var linksy = "http://click.linksynergy.com/fs-bin/click?id=r10gDeJMIGc&subid=&offerid=146261.1&type=10&tmpid=3909&u1=chuaizhe&RD_PARM1=" + itunesUrl.replace("itms","http");
	$("#download-" + appid).attr("href",linksy);
	$("#download-small-" + appid).attr("href",linksy);
	$("#popup-download-button").attr("href",linksy);
}

function addWFR(appid,itunesUrl){
	$.getJSON("/api/20/download-mark/?id=" + appid + "&mark=r",function(data){
		wfrCallBack(appid,data,itunesUrl);
	});
}

function wfrCallBack(appid,data,itunesUrl){
	var path = location.pathname;
	if(0 == path.indexOf("/app/")){
		refreshPage();
		return;
	}else if(0 == path.indexOf("/recommended/")){
		increaseWFR(appid,data,itunesUrl);
	}else if(0 == path.indexOf("/price-drops/")){
		updateButtonWFR(appid);
		increaseWFR(appid,data,itunesUrl);
		updatePriceDropDicount(data);
	}else if(0 == path.indexOf("/tag/")){
		updateButtonWFR(appid);
		increaseWFR(appid,data,itunesUrl);
	}else if(0 == path.indexOf("/users/")){
		if(0 >= path.indexOf("/wish/") || $("#isself").text() != "true"){
			updateButtonWFR(appid);
			increaseWFR(appid,data,itunesUrl);
		}else{
			increaseWFRNum();
			reduceWishNum();
		}
	}else if(0 == path.indexOf("/lists/") || 0 == path.indexOf("/search/") || 0 == path.indexOf("/")|| 0 == path.indexOf("/top/")){
		updateListWFR(appid);
		increaseWFR(appid,data,itunesUrl);
	}else{
		refreshPage();
		return;
	}
}

function updateListWFR(app_id){
	if(!isLogin()){
		return;
	}
	if($("#orininalMark-" + app_id).text() == "w"){
		var actionBox = $("#app_" + app_id).find(".app-action");
		var htmls = "<a onclick='userReview(" + app_id + ",\"u\")' href='javascript:;' class='vote' id='vote-" + app_id + "'>评分</a><a onclick='userReview(" + app_id + ",\"w\")' href='javascript:;' class='wish' id='wish-" + app_id + "'>想要</a>";
		actionBox.html(htmls);
	}
}

function updateButtonWFR(app_id){
	if(!isLogin()){
		return;
	}
	if($("#orininalMark-" + app_id).text() == "w"){
		var actionBox = $("#download-" + app_id).parent();
		var htmls = "<a onclick='userReview(" + app_id + ",\"u\")' class='smallButton' id='vote-" + app_id + "' href='javascript:;'>评分</a><a onclick='userReview(" + app_id + ",\"w\")' class='smallButton' id='wish-" + app_id + "' href='javascript:;'>想要</a>";
		actionBox.find("a[id^='vote']").add(actionBox.find("a[id^='wish']")).add(actionBox.find("a[id^='delete']")).remove();
		actionBox.prepend(htmls);
	}
}

function increaseWFR(app_id,data,itunesUrl){
	status = data.status;
	if(status && status != "false"){
		increaseWFRNum();
		if($("#orininalMark-" + app_id).text() == "w"){
			reduceWishNum();
		}
		$("#orininalMark-" + app_id).text("r");
	}
}

function increaseWFRNum(){
	$(".wfr-num").text(parseInt($("#wfr-num").text()) + 1);
}

function reduceWFRNum(){
	var wfrNum = parseInt($("#wfr-num").text()) - parseInt(1);
	$(".wfr-num").text(wfrNum);
}

function updatePriceDropDicount(data){
	try{
		var amount = data.save_money;
		var count = data.save_count;
		$("#price-drop-amount").text("$" + (parseFloat(amount)).toFixed(2));
		$("#price-drop-amount").attr("title","约合人民币" + ((parseFloat(amount*6.5)).toFixed(2)) + "元");
	}catch(e){
		return;
	}
}


//Pre Loading Images
function hideVerticalAppsImages(con){
	var items = $("#" + con + " .app-logo-mid");
	var imgs = new Array();
	$.each(items,function(i){
		items[i] = $(items[i]);										
		imgs.push(items[i].css("background-image"));	
		items[i].css("background","none");
	});
	$("#" + con).data("imgs",imgs);
}

function bindAnimationImgs(pageNum){
	var page = $(".animation-h-box .showbox-h li")[pageNum - 1];
	var logos = $(page).find(".app-logo-big");
	if("none" != logos.css("background-image")){
		return;
	}
	$.each(logos,function(i){
		$(this).attr("style",$(this).attr("original"));
	});
}

//Cookie
function getCookie(c_name){
	if (document.cookie.length>0){
		c_start=document.cookie.indexOf(c_name + "=")
		if(c_start!=-1){ 
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if(c_end==-1){
				c_end=document.cookie.length;
			}
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	return ""
}

function setCookie(name,value){ 
	expires = new Date(); 
	expires.setTime(expires.getTime() + (1000 * 86400 * 365)); 
	document.cookie = name + "=" + escape(value) + "; expires=" + expires.toGMTString() + "; path=/"; 
}

function delCookie(name){ 
	var exp = new Date(); 
	exp.setTime(exp.getTime() - 1); 
	var cval=getCookie(name); 
	if(cval!=null) document.cookie= name + "='';expires="+exp.toGMTString(); 
}

//Direct Vote
function bindDirectVoteImgEvent(appid){
	$("#direct-vote img").click(function(){
		userReview(appid,'u');
	});
	$("#review-body .popup-close a").click(function(){
		$(".review_score").val(0);
		showStarScore("#direct-vote-form");
	});
}

//Ajax Load App List

//bind pre and next button event
function bindApps9NextEvent(){
	$(".next-button").click(function(){
		next9Apps();
	});
}

function bindApps9PreEvent(){
	$(".pre-button").click(function(){
		pre9Apps();
	});
}

function loadApps(condition){
	var appType = getAppsType();
	var url = "/api/20/" + appType + "/";
	try{		
		$.ajax({
			type:"GET",
			url:url,
			data:condition,
			dataType:"json",
			timeout:25000,
			success:function(data){
				if(condition.start == 0){
					$("#total-num").text(Math.ceil(data.total/9));
					$("#total-app-num").text("（共" + data.total + "个）");
				}
				if("undefined" != data.code && "401" == data.code){
					$("#apps-9-animation ul").html("<li><h2>没有匹配的应用。</h2></li>");
					$("#loading-image").hide();
					return;
				}
				checkApps9More(data.has_more,data.items.length,9);
				if(0 == condition.start){
					//load 2 pages show first page and hide second
					paint9AppsFirstPage(data,appType);
					$(".pre-button").addClass("a-btn-disable");
					if(data.items.length <= 9){
						$("#max-pagenum").text(1);
					}
					$("#loading-image").hide();
				}else{
					//paint next page
					paint9Apps(data,appType);
				}
				//After API update, we will have max length of the list, then the check app more method will
				//be update too. First page issue will be fixed too.
			},
			error:function(XMLHttpRequest, textStatus, errorThrown){
				if("timeout" == textStatus){
					alert("抱歉，您这次访问花费的时间比平时长,请检查您的网络连接或者重新刷新试试 ◑﹏◐");
				}
			}
		});
	}catch(e){
		alert(e);
	}
}

function loadUserApps(condition){
	var url = "/api/20/user/";
	try{		
		$.ajax({
			type:"GET",
			url:url,
			data:condition,
			dataType:"json",
			timeout:25000,
			success:function(data){
				checkApps9More(data.has_more,data.items.length,10);
				if(0 == condition.start){
					$(".pre-button").addClass("a-btn-disable");
				}else{
					$(".pre-button").removeClass("a-btn-disable");
				}
				paintUserApps(data);
			},
			error:function(XMLHttpRequest, textStatus, errorThrown){
				if("timeout" == textStatus){
					alert("抱歉，您这次访问花费的时间比平时长,请检查您的网络连接或者重新刷新试试 ◑﹏◐");
				}
			}
		});
	}catch(e){
		alert(e);
	}
}

function checkApps9More(has_more,itemsNum,maxNum){
	if(!has_more && parseInt(itemsNum) <= maxNum){
		$("#max-pagenum").text(parseInt($("#current-pagenum").text()) + 1);
		$(".next-button").addClass("a-btn-disable");
	}else{
		$(".next-button").removeClass("a-btn-disable");
	}
}

function getAppsType(){
	var type = $("#list-type").text();
	if(type.indexOf("tag") >= 0){
		type = "tag";
	}
	return type;
}

function paint9Apps(data,type){
	var preData = data.items;
	var targetPage = $("#current-pagenum").text();
	var preHtml = $("<li id='apps9-" + (parseInt(targetPage) + 1) + "'></li>");
	preHtml = getApp9HTML(preHtml,preData,type);
	$("#apps9-" + parseInt(targetPage)).data("next",preHtml);
}

function paintUserApps(data){
	var apps = data.items;
	var newHtml = getUserAppsHTML(apps);
	$("#user-apps").hide().html(newHtml).fadeIn();
}

function paint9AppsFirstPage(data,type){
	var apps = data.items;
	if(data.length <= 9){
		$("#max-pagenum").text("1");
	}else{
		$("#max-pagenum").text("");
	}
	var targetPage = $("#current-pagenum").text();
	var showHtml = $("<li class='hidden' id='apps9-" + parseInt(targetPage) + "'></li>");
	var preHtml = $("<li id='apps9-" + (parseInt(targetPage) + 1) + "'></li>");
	var showData;
	var preData;
	if(9 < apps.length){
		showData = apps.slice(0,9);
		preData = apps.slice(9,apps.length);
	}else{
		showData = apps;
	}
	showHtml = getApp9HTML(showHtml,showData,type);
	if("undefined" != typeof(preData) && 0 != preData.length){
		preHtml = getApp9HTML(preHtml,preData,type);
		$("#apps9-" + parseInt(targetPage)).data("next",preHtml);
	}
	$("#apps-9-animation ul").append(showHtml);
	$("#apps-9-animation ul li").fadeIn();
	
}

function getApp9HTML(con,apps,type){
	if("recommendation" == type && apps.length == 0){
		var img = "guess1";
		if("old" == isNew){
				img = "guess2";
		}
		con.append("<center><img src='/media/static/images/" + img + ".jpg' /></center>");
		$(".apps-9field-action a").addClass("a-btn-disable");
		$(".apps-9field-header").css("margin-bottom","0");
		$(".apps-9field-footer").css("margin-top","0");
		return con;
	}
	$("#recommended-desc").show();
	$.each(apps,function(i){
		var line = createApp9Box(apps[i],type);
		if(0 == (i+1)%3){
			line.css("border-right","none");
		}
		if(i > 5){
			line.css("border-bottom","none");
		}
		con.append(line);
	});
	return con;
}

function getUserAppsHTML(apps){
	var temp = $("<div></div>");
	$.each(apps,function(i){	
		temp.append(createUserApps9Box(apps[i].app));
	});
	return temp;
}

function createApp9Box(app,type){
	return createNormalApps9Box(app);
}

function createNormalApps9Box(app){
	var temp = paintSimpleApps9Box(app);
	temp = addNormalApps9Action(temp,app);
	return temp;
}

function paintSimpleApps9Box(app){
	var temp = $("#app-9field-template").clone();
	temp.find(".app-9-logo").css("background-image","url(/media/" + app.middle_logo + ")");
	temp.find(".app-9-logo a").attr("href","/app/" + app.appid + "/");
	temp.find("h2").attr("id","name-" + app.appid)
	temp.find("h2 a").text(app.name);
	temp.find("h2 a").attr("href","/app/" + app.appid + "/");
	if(0 == app.price && !app.pricedrop){
		temp.find(".app-9-price").text("免费");
		temp.find(".app-9-price").addClass("small-free-mark");
	}else if(0 == app.price && app.pricedrop){
		temp.find(".app-9-price").text("限时免费").attr("title","更新时间：" + app.price_update_date);
		temp.find(".app-9-price").addClass("small-discount-mark");
	}else if(0 != app.price && app.pricedrop){
		temp.find(".app-9-price").text("$" + app.price);
		temp.find(".app-9-price").addClass("small-limit-mark");
	}else{
		temp.find(".app-9-price").text("$" + app.price);
		temp.find(".app-9-price").addClass("small-price-mark");
	}
	temp.find(".app-9-price").click(function(){
		showDownload(this);
	});
	
	temp.find(".hidden-isPriceDrop").text(app.pricedrop).attr("id","ispricedrop-" + app.appid);
	temp.find(".hidden-price").text(app.price).attr("id","price-" + app.appid);
	if(app.pricedrop){
		temp.find(".hidden-original-price").text(("undefined" != typeof(app.original_price))?app.original_price:"0,99").attr("id","original-price-" + app.appid);
	}
	temp.find(".download-button").attr("id","download-" + app.appid).click(function(){
		return openDownloadPage(app.itunes,app.appid);
	});
	temp.find(".app-score span:first").attr("class","star" + app.star_num);
	temp.find(".score-number").text(app.score);
	temp.find(".app-9-tags").text(app.tags_str);
	temp.find(".app-attention-num").text(app.interesting);
	if("undefined" != typeof(app.mur)){
		temp.find(".app-9-comment a").attr("href","/users/" + app.mur.user.username +"/")
		.text(app.mur.user.nick_name + " : ")
		.after(app.mur.content);
	}else{
		temp.find(".app-9-comment").hide();
	}
	temp.find(".orininalMark").attr("id","orininalMark-" + app.appid).text(app.user_mark);
	temp.attr("id","app-9field-" + app.appid).removeClass("hidden");
	return temp;
}

function addNormalApps9Action(con,app){
	var temp = con;
	if("undefined" == typeof(app.user_mark)){
		temp.find(".actions").prepend("<a href='javascript:;' id='vote-" + app.appid + "' class='smallButton' onclick='userReview(" + app.appid + ",\"u\")'>评分</a><a href='javascript:;' class='smallButton' id='wish-" + app.appid + "' onclick='userReview(" + app.appid + ",\"w\")'>想要</a>");
	}else if("w" == app.user_mark){
		temp.find(".actions").prepend("<a href='javascript:;' id='vote-" + app.appid + "' class='smallButton' onclick='userReview(" + app.appid + ",\"u\")'>评分</a><a id='wish-" + app.appid + "' href='javascript:;' class='smallButton smallButton-selected'>想要</a>");
	}else if("u" == app.user_mark){
		temp.find(".actions").prepend("<a href='javascript:;' id='vote-" + app.appid + "' class='smallButton' onclick='userReview(" + app.appid + ",\"m\")'>修改</a><a id='delete-" + app.appid + "' href='javascript:;' class='smallButton' onclick='deleteReview(" + app.appid + ")'>删除</a>");
	}else if("r" == app.user_mark){
		temp.find(".actions").prepend("<a href='javascript:;' id='vote-" + app.appid + "' class='smallButton' onclick='userReview(" + app.appid + ",\"u\")'>评分</a><a href='javascript:;' id='wish-" + app.appid + "' class='smallButton' onclick='userReview(" + app.appid + ",\"w\")'>想要</a>");
	}
	
	//ignore button control
	if("recommendation" == $("#list-type").text()){
		temp.find(".ignore-button").click(function(){
			ignoreApp(app.appid);
		});
		temp.bind("mouseover",function(){
			temp.find(".ignore-button").show();
		}).bind("mouseout",function(){
			temp.find(".ignore-button").hide();
		});
	}
	return temp;
}

function refresh9App(){
	var currentPageNum = $("#current-pagenum").text();
	var currentPage = $("#apps9-" + currentPageNum);
	var apps = currentPage.find(".app-9field");
	apps.css({
		"border-bottom":"1px dashed #CCC",
		"border-right":"1px dashed #CCC" 
	});
	$.each(apps,function(i){
		if(0 == (i+1)%3){
			$(apps[i]).css("border-right","none");
		}
		if(i>5){
			$(apps[i]).css("border-bottom","none");
		}
	});
	if(0 == apps.length && 0 == location.pathname.indexOf("/recommended/")){
		currentPage.append("<h2>再换一组试试看吧！</h2>");
	}
}


function next9Apps(){
	var maxPageNum = parseInt($("#max-pagenum").text());
	var currentPage = parseInt($("#current-pagenum").text());
	if(maxPageNum == currentPage){
		return;
	}
	if(maxPageNum == (currentPage + 1)){
		$(".next-button").addClass("a-btn-disable");
	}
	var nextPage = $("#apps9-" + (currentPage + 1));
	var current = $("#apps9-" + currentPage);
	$(".next-button").addClass("rectangle-button-selected");
	$("#apps9-" + currentPage).find(".app-9field").addClass("hidden");
	$("#loading-image").show();
	if(0 != nextPage.length){
		moveToNext(parseInt(currentPage) + 1);
		$("#current-pagenum").text(parseInt(currentPage) + 1);
		$(".pre-button").removeClass("a-btn-disable");
		return;
	}
	var condition = getApps9Condition();
	condition.start = currentPage * 9
	condition.size = 9;
	loadApps(condition);
	var nextPageHtml = $("#apps9-" + (currentPage + 1)).data("next");
	if(null != nextPageHtml && "" != nextPageHtml && "undefined" != typeof(nextPageHtml)){
		transNextApp9(currentPage,nextPageHtml);
	}else{
		var nextRequestId = setInterval(function(){
			nextPageHtml = $("#apps9-" + currentPage).data("next");
			if(null != nextPageHtml && "" != nextPageHtml && "undefined" != typeof(nextPageHtml)){
				transNextApp9(currentPage,nextPageHtml);
				clearInterval(nextRequestId);
			}
		},300)
	}
}

function moveToNext(targetPageNum){
	$("#loading-image").hide();
	$(".next-button").removeClass("rectangle-button-selected");
	$("#apps9-" + targetPageNum).find(".app-9field").removeClass("hidden");
	$("#apps-9-animation").animate({
		left: '-=' + 960
	},500);
}

function moveToPre(targetPageNum){
	//if(!isIpad()){
		$("#apps9-" + (parseInt(targetPageNum) + 1)).find(".app-9field").addClass("hidden");
		$("#apps9-" + parseInt(targetPageNum)).find(".app-9field").removeClass("hidden");
		$("#apps-9-animation").animate({
			left: '+=' + 960
		},500);
	//}else{
	//	$("#apps-9-animation").css("left",parseInt($("#apps-9-animation").css("left")) + 918);
	//}
}

function nextUserApps(){
	var maxPageNum = parseInt($("#max-pagenum").text());
	var currentPage = parseInt($("#current-pagenum").text());
	if(maxPageNum == currentPage + 1){
		return;
	}
	if(maxPageNum == (currentPage + 1)){
		$(".next-button").addClass("a-btn-disable");
	}
	var condition = getApps9Condition();
	condition.start = currentPage * 10
	condition.size = 10;
	loadUserApps(condition);
	$("#current-pagenum").text(parseInt(currentPage) + 1);
}

function pre9Apps(){
	var currentPage = parseInt($("#current-pagenum").text());
	
	if(currentPage != 1){
		$("#current-pagenum").text(currentPage - 1)
	}else{
		return;
	}
	moveToPre(currentPage - 1);
	if(currentPage == parseInt($("#max-pagenum").text())){
		$(".next-button").removeClass("a-btn-disable");
	}
	if(2 == currentPage){
		$(".pre-button").addClass("a-btn-disable");
	}
}

function preUserApps(){
	var currentPage = parseInt($("#current-pagenum").text());
	if(currentPage == (parseInt($("#max-pagenum").text()) - 1)){
		$(".next-button").removeClass("a-btn-disable");
	}
	if(currentPage != 1){
		$("#current-pagenum").text(currentPage - 1)
	}else{
		return;
	}
	var condition = getApps9Condition();
	condition.start = (currentPage - 2) * 10
	condition.size = 10;
	loadUserApps(condition);
}

function transNextApp9(currentPage,nextPageHtml){
	$("#apps-9-animation ul").append(nextPageHtml);
	moveToNext((parseInt(currentPage) + 1));
	//var final_x = parseInt($("#apps-9-animation").css("left").replace("px","")) - 918;
	//moveElem("apps-9-animation", final_x, 0, 600);
	$("#apps9-" + currentPage).removeData("next");
	$("#current-pagenum").text(parseInt(currentPage) + 1);
	$(".pre-button").removeClass("a-btn-disable");
}

function load9AppsFirstPage(){
	var condition = getApps9Condition();
	condition.start = 0;
	condition.size = 18;
	$("#loading-image").show();
	loadApps(condition);
	bindApps9NextEvent();
	bindApps9PreEvent();
}

function getApps9Condition(){
	var condition = {
		"tag-name":$("#list-type").text().replace("tag_",""),
		"device":$("#driver span").text(),
		"price":$("#price span").text(),
		"order":$("#order span").text(),
		"ex_mine":$("#check-mine span").text(),
		"type":$("#filter-user-type").text()//user action type (wish or used)
	}
	return condition;
}

function paintApps9Paging(num){
	var pagingHtml = "";
	for(var i=0;i<num;i++){
		pagingHtml += "<a href='javascript:;' id='apps9-paging-" + (i + 1) + "'>" + (i + 1) + "</a>";
	}
	$("#apps-9-paging").html(pagingHtml);
	$("#apps-9-paging a").click(function(){
		transToApps9Page($(this).attr("id").replace("apps9-paging-",""));
	});
}

function transToApps9Page(pageNum){
	var leftWidth = (parseInt(pageNum) - 1) * 918;
	var targetPage = $("#apps9-" + pageNum);
	if(0 != targetPage.length){
		$("#apps-9-animation").animate({
			left: '-' + leftWidth
		},400);
	}else{
		
	}
	$("#current-pagenum").text(pageNum);
}

function selectFilter(con){
	var parent = $(con).parent();
	var valueField = parent.find("span").text($(con).attr("value"));
	var old = parent.find("a[class$='selected']");
	if(0 != old.length){
		old.attr("class",old.attr("class").replace("-selected",""));
	}
	$(con).attr("class",$(con).attr("class") + "-selected");
}

function selectCheckBox(con){
	con = $(con);
	var v = (con.find("em").attr("class").indexOf("checked")>=0)?false:true;
	if(v){
		con.find("em").removeClass("checkbox-icon").addClass("checkbox-checked-icon");
	}else{
		con.find("em").removeClass("checkbox-checked-icon").addClass("checkbox-icon");
	}
	con.parent().find("span").text(v);
}

function getApp9ByFilter(){
	loadApps9ByFilter();
}

function selectTagFilter(con){
	con = $(con);
	var old = $(".category-filter").find("span");
	old.replaceWith("<a href='javascript:;' title='" + old.attr("title") + "' onclick='selectTagFilter(this)'>" + old.text() + "</a>");
	con.replaceWith("<span title='" + con.attr("title") + "' class='selected'>" + con.text() + "</span>");
	$("h1").text("标签：" + con.attr("title"));
	$("#list-type").text("tag_" + con.attr("title"));
	loadApps9ByFilter();
	$(".apps-9field-action").show();
}

function loadApps9ByFilter(){
	var condition = getApps9Condition();
	condition.start = 0;
	condition.size = 18;
	$("#current-pagenum").text(1);
	$("#apps-9-animation").css("left","0px");
	$("#apps-9-animation ul").empty();
	$("#loading-image").show();
	loadApps(condition);
}

function loadUserAppsByFilter(){
	var condition = getApps9Condition();
	condition.start = 0;
	condition.size = 10;
	condition.id = $("#filter-user-id").text();
	$("#current-pagenum").text(1);
	loadUserApps(condition);
}

function selectInitialTag(){
	var tagname = $("h1").text().replace("标签：","");
	var tags = $(".category-filter a");
	$.each(tags,function(i){
		if(tagname == $(tags[i]).attr("title")){
			$(tags[i]).replaceWith("<span title='" + $(tags[i]).attr("title") + "' class='selected'>" + $(tags[i]).text() + "</span>");
		}
	});
}

function touchActions(){
	if(!isIpad){
		return;
	}
	try{
		var startX = 0;
		var startY = 0;
		var endX = 0;
		var endY = 0;
		
		var content = $(".content")[0];
		content.addEventListener("touchstart", touchStart, false);
		content.addEventListener("touchend", touchEnd, false);
		
		function touchStart(){
			event.preventDefault();
			startX = event.targetTouches[0].pageX;
			startY = event.targetTouches[0].pageY;
			alert(startX);
		}
		
		function touchEnd(){
			event.preventDefault();
			endX = event.targetTouches[0].pageX;
			endY = event.targetTouches[0].pageY;
			alert(endX);
		}
	}catch(e){
		return;
	}
}

//Top Api

function loadTop(type){
	var url = "/api/20/top/";
	condition.device = $("#driver span").text();
	condition.price = $("#price span").text();
	if("undefined" != typeof(type) && "filter" == type){
		condition.start = 0;
		$(".top-loading").show();
	}
	if("undefined" != typeof(type) && "more" == type){
		$("#full-more-button a").text("加载中...");
		condition.start = condition.start + condition.size;
	}
	try{		
		$.ajax({
			type:"GET",
			url:url + "?category=game",
			data:condition,
			dataType:"json",
			timeout:25000,
			success:function(data){
				paintTop(data,condition.start,"game");
				//After API update, we will have max length of the list, then the check app more method will
				//be update too. First page issue will be fixed too.
			},
			error:function(XMLHttpRequest, textStatus, errorThrown){
				if("timeout" == textStatus){
					alert("抱歉，您这次访问花费的时间比平时长,请检查您的网络连接或者重新刷新试试 ◑﹏◐");
				}
			}
		});	
		$.ajax({
			type:"GET",
			url:url + "?category=app",
			data:condition,
			dataType:"json",
			timeout:25000,
			success:function(data){
				paintTop(data,condition.start,"app");
				//After API update, we will have max length of the list, then the check app more method will
				//be update too. First page issue will be fixed too.
			},
			error:function(XMLHttpRequest, textStatus, errorThrown){
				if("timeout" == textStatus){
					alert("抱歉，您这次访问花费的时间比平时长,请检查您的网络连接或者重新刷新试试 ◑﹏◐");
				}
			}
		});
	}catch(e){
		alert(e);
	}
}

function paintTop(data,start,type){
	if("game" == type){
		topData.games = data;
	}else{
		topData.apps = data;
	}
	if(topData.games == "" || topData.apps == ""){
		return;
	}
	$(".top-loading").hide();
	var gameHtml = getTopHtml(topData.games.items,start);
	var softwareHtml = getTopHtml(topData.apps.items,start);
	topData.games = "";
	topData.apps = "";
	if(start == 180){
		$("#full-more-button").hide();
	}else{
		$("#full-more-button a").text("更多");
		$("#full-more-button").show();
	}
	if(start == 0){
		$("#game-top .top-list-content").empty().append(gameHtml);
		$("#software-top .top-list-content").empty().append(softwareHtml);
	}else{
		$("#game-top .top-list-content").append(gameHtml);
		$("#software-top .top-list-content").append(softwareHtml);
	}
}

function getTopHtml(apps,start){
	var staticHtml = $("<div></div>");
	var order;
	$.each(apps,function(i){
		order = start + i + 1;
		staticHtml.append(createTopApp(apps[i],order));
	});
	return staticHtml.contents();
}

function createTopApp(app,order){
	var temp = $("#app-box-template").clone();
	temp.find("a:first").attr("title",app.name).attr("href","/app/" + app.appid + "/");
	temp.find(".app-logo-min").css("background-image","url(/media/" + app.logo + ")");
	temp.find(".list-app-title a").attr("title",app.name).attr("href","/app/" + app.appid + "/");
	temp.find(".list-app-title a").text(order + ". " + app.name);
	temp.find(".app-tags").text(app.tags_str);
	temp.find(".app-score span:first").attr("class","star" + app.star_num);
	temp.find(".app-score span:last").text("(" + app.interesting + "人关注)");
	if(0 == app.price && !app.pricedrop){
		temp.find(".app-box-price").append("<a href='javascript:;' onclick='showDownload(this)' class='price-free'>免费</a>");
	}else if(0 == app.price && app.pricedrop){
		temp.find(".app-box-price").append("<a href='javascript:;' title='更新时间：" + app.price_update_date + "' onclick='showDownload(this)' class='price-discount'>$" + app.original_price + "</a><div class='price-supply'>限时免费</div>");
	}else if(0 != app.price && app.pricedrop){
		temp.find(".app-box-price").append("<a href='javascript:;' onclick='showDownload(this)' class='price-limit'>$" + app.price + "</a><div class='original-mark price-supply'>&nbsp;$" + app.original_price + "&nbsp;</div>");
	}else{
		temp.find(".app-box-price").append("<a href='javascript:;' onclick='showDownload(this)' class='price-normal'>$" + app.price + "</a>");
	}
	temp.find(".app-box-price").prepend("<a id='download-" + app.appid + "' target='_blank' class='price-download' onclick='return openDownloadPage(\"" + app.itunes + "\",\"" + app.appid + "\")' style='display:none' href='javascript:;'>下载</a>");
	temp.find(".hidden-isPriceDrop").text(app.pricedrop).attr("id","ispricedrop-" + app.appid);
	temp.find(".hidden-price").text(app.price).attr("id","price-" + app.appid);
	if(app.pricedrop){
		temp.find(".hidden-original-price").text(app.original_price).attr("id","original-price-" + app.appid);
	}
	temp.attr("id","app_" + app.appid);
	temp.removeClass("hidden");
	return temp;
}

//Move App To Waiting for Review
function moveToWFR(appid,itunesUrl){
	
	var appBox = $("#app_" + appid);
	var wfrBox = $(".right-box-content");
	var appIcon = appBox.find("a:first");
	appIcon = appIcon.clone();
	appIcon.attr("href",$(".right-box-header a").attr("href"));
	appIcon.find("img").attr("src","/media/static/images/60mask.png");
	appIcon.attr("id","app-wfr-" + appid);
	appIcon.find(".app-logo-mid").attr("class","app-logo-min").attr("style","background-image:url(/media/" + appIcon.find(".app-logo-min").attr("minlogo") + ")");
	moveAtoB(appBox,wfrBox,function(){
		$("#app_" + appid).remove();
		refreshMineApps();
		if(0 == $("#app-wfr-" + appid).length){
			wfrBox.prepend(appIcon);
			addWFR(appid);
		}
		if(12 == wfrBox.find("a").length){
			wfrBox.find("a:last").remove();
			$("#all-wfr").show();
		}
		window.open(itunesUrl.replace("itms","http"));
	});
}

function refreshMineApps(app_id){
	$(".profile-mine-page .dashed-line").remove();
	$(".profile-mine-page .app-box-advance").css("border","none");
	$(".profile-mine-page .app-box-advance:even").css("border-right","1px dashed #CCC");
	$(".profile-mine-page .app-box-advance:odd").after("<div class='dashed-line clear'></div>");
}


/* update app comments */
function loadComments(id,order){
	if("" == $.trim($("#comments-by-useful").html())){
		var url = "/api/20/comments/";
		var condition = {
			"id":id,
			"order":order,
			"size":10,
			"start":0
		}
		$.getJSON(url,condition,function(data){
			paintComments(data);
		});
	}else{
		$('#comments-by-useful').show();
		$('#comments-by-update').hide();
	}
}

function paintComments(data){
	$("#comments-by-update").hide();
	$("#comments-by-useful").append(getCommentsHTML(data.items)).show();
}

function getCommentsHTML(comments){
	var htmls = $("<div></div>");
	$.each(comments,function(i){
		htmls.append(createCommentLine(comments[i]));
	});
	return htmls.html();
}

function createCommentLine(comment){
	var temp = $("#comment-template").clone();
	temp.find(".comment-avatar a").attr("href","/users/" + comment.user.username + "/");
	temp.find(".comment-avatar img").attr("src",comment.user.avatar).attr("title",comment.user.nick_name).attr("alt",comment.user.nick_name);
	temp.find(".comment-head span:first a").text(comment.user.nick_name).attr("href","/users/" + comment.user.username + "/");
	temp.find(".comment-star").addClass("star" + comment.score + "0");
	temp.find(".comment-time").text(comment.update_date);
	temp.find(".comment-content p").text(comment.content);
	temp.find(".comment-action span").attr("id","comment_" + comment.id + "_num").text(comment.useful);
	temp.find(".comment-action a").attr("onclick","markUseful(" + comment.id + ",this)");
	temp.attr("id","comment-" + comment.id);
	temp.removeClass("hidden");
	return temp;
}

function bindEmail(){
	var isPost = true;
	$(".error").empty();
	var condition = {
		"email":$.trim($("#id_email").val()),
		"password1":$("#id_password1").val(),
		"password2":$("#id_password2").val()
	}
	if(condition.email == ""){
		$("#id_email").next(".error").text("必填");
		isPost = false;
	}else if(!verifyEmail(condition.email)){
		$("#id_email").next(".error").text("请输入正确的Email地址");
		isPost = false;
	}
	if(condition.password1 == ""){
		$("#id_password1").next(".error").text("必填");
		isPost = false;
	}else if(condition.password1.length < 4){
		$("#id_password1").next(".error").text("密码至少为4位");
		isPost = false;
	}
	if(condition.password2 == ""){
		$("#id_password2").next(".error").text("必填");
		isPost = false;
	}else if(condition.password2 != condition.password1){
		$("#id_password2").next(".error").text("前后密码不一致");
		isPost = false;
	}
	if(isPost){
		$.post("/api/20/bind-email/",condition,function(data){
			if("{}" == data){
				refreshPage();
			}else{
				data = transJSON(data);
				alert(data.message);
			}
		});
	}
}

function deleteTopicReply(replyid){
	$.get("/reply/" + replyid + "/delete/",function(data){
		if("undefined" == typeof(data.code)){
			$("#topic-reply-" + replyid).remove();
		}
	})
}

function checkTopic(){
	$(".error").text("");
	$("#id_content").val(tinyMCE.get("id_content").getContent());
	var condition = {
		"title":$("#id_title").val(),
		"group":($("#id_group").length != 0)?$("#id_group").val():null,
		"content":$("#id_content").val()
	}
	var isPost = true;
	
	if("" == condition.title){
		$("#id_title").next().text("请输入您的标题");
		isPost = false;
	}else{
		if(condition.title.length > 30){
			$("#id_title").next().text("您输入的标题太长了，请缩短到30个字以内吧");
			isPost = false;
		}
	}
	
	if(null != condition.group){
		if("" == condition.group){
			$("#id_group").next().text("请选择一个小组");
			isPost = false;
		}
	}
	
	var pureText = $(tinyMCE.getInstanceById("id_content").getBody()).text();
	var fullContent = $("#id_content").val();
	var isImage = fullContent.indexOf("<img");
	if("" == pureText && -1 == isImage){
		$("#id_content").parent().parent().find(".error").text("您还什么都没输入呢");
		isPost = false;
	}else if("" == pureText && isImage >= 0){
		$("#id_content").parent().parent().find(".error").text("光插入图片可是不行的哦，再说点什么吧");
		isPost = false;
	}else if(3 > condition.content.length > 0){
		$("#id_content").parent().parent().find(".error").text("您的发言太短了");
		isPost = false;
	}
	
	return isPost;
}

function checkTopicReply(){
	if($("#topic-reply-button").attr("class").indexOf("rectangle-small-button-disable") >= 0){
		return false;
	}
	$(".error").text("");
	var content = $("#id_content").val();
	if("" == content){
		$(".error").text("您还什么都没输入呢...");
		return false;
	}
	if(300 < content.length){
		$(".error").text("您输入的内容太长了，请缩短到300个字以内吧...");
		return false;
	}
	$("#topic-reply-button").hide();
	$("#topic-reply-button-disable").show();
	return true;
}

function myTinyMCE(inst) {
	$("#id_content").text(inst.getBody().innerHTML);
}

/* Friends */
function follow(username){
	var url = "/api/20/add-friend/?username=" + username;
	$.get(url,function(data){
		if("{}" == data){
			$("#follow-" + username).replaceWith("<a class='unfollow' id='unfollow-" + username + "' href='javascript:;' onclick='unfollow(\"" + username + "\")'>取消关注</a>");
		}
	})
}

function unfollow(username){
	var url = "/api/20/del-friend/?username=" + username;
	$.get(url,function(data){
		if("{}" == data){
			$("#unfollow-" + username).replaceWith("<a id='follow-" + username + "' class='orange-btn-s orange-btn-b' href='javascript:;' onclick='follow(\"" + username + "\")'>+加关注</a>");
		}
	})
}

function toggleSyncAccount(){
	if($("#isPostWeibo").attr("checked")){
		$("#link_submit").attr("href","/social/bind?action=create-new-user&sync=true");
		$("#id_sync").val("true");
	}else{
		$("#link_submit").attr("href","/social/bind?action=create-new-user");
		$("#id_sync").val("false");
	}
}

var subjects = [
	{"name":"浏览器","keywords":"浏览器","cls":"browser"},
	{"name":"社交工具","keywords":"聊天SNS","cls":"imsns"},	
	{"name":"在线视频","keywords":"在线视频","cls":"onlinevideos"},
	{"name":"全景相机","keywords":"全景相机","cls":"camera360"},	
	{"name":"照相必备","keywords":"照相必备","cls":"cameras"},
	{"name":"LBS","keywords":"LBS","cls":"LBSs"},
	{"name":"腾讯","keywords":"腾讯","cls":"tencent"},
	{"name":"聚合阅读","keywords":"聚合阅读","cls":"polymerize"},
	{"name":"声控","keywords":"声控","cls":"voicecontrol"},
	{"name":"语音","keywords":"语音","cls":"voice"}
];

function getSubjects(num){
	var selectSubjects = new Array()
	var a = new Array();
	var index;
	for(var i=0; i<num;i++){
		do{
			index = Math.ceil(Math.random() * subjects.length);
		}	while($.inArray(index,a) != -1)
		a.push(index);
		selectSubjects.push(subjects[index-1]);
	}
	return selectSubjects;
}

function showSubjects(num){
	num = parseInt(num);
	var selectSubjects = getSubjects(num);
	var htmls = '';
	for(var i=0;i<num;i++){
		htmls += getSubjectHtml(selectSubjects[i],i)
	}
	$("#subjects-suggests").append(htmls);
}

function getSubjectHtml(subject,i){
				return "<a onclick='_gaq.push([\"_trackEvent\", \"index\", \"p" + (i+1) + "\", \"" + subject.name + "\" ,0])' class='subject subject-" + subject.cls + "' href='/search/?keyword=" + subject.keywords + "'><em></em>" + subject.name + "</a>";
}

function checkProfileUpdate(){
	if($("#id_nick_name").val().indexOf("揣着") != -1){
		$("#id_nick_name").next().text("昵称不能包含揣着哦");
	}else{		
		$('.form-box').submit();
	}
}